import { useEffect, useRef, useState } from "react";
// 排除值为0
export const isFalsy = (value: unknown): boolean => value === 0 ? false : !value;

export const isVoid = (value: unknown): boolean => value == null || value === "";

// 在一个函数里，改变传入的对象的本身是不好的
export const clearObject = (object: { [key: string]: unknown }) => {
  // Object.assign({}, object)
  const result = { ...object };
  Object.keys(result).forEach(key => {
    const value = result[key];
    if (isVoid(value)) {
      delete result[key];
    }
  });
  return result;
};

export const useMount = (callback: () => void) => {
  useEffect(() => {
    callback();
    // TODO 依赖项里面的callback会造成无线循环，这个和useCallback以及useMemo有关系
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
};

export const useDebounce = <V> (value: V, delay?: number): V => {
  const [debounceValue, setDebounceValue] = useState(value);
  useEffect(() => {
    // 每次在value变化以后，设置一个定时器
    const timeout = setTimeout(() => setDebounceValue(value), delay);
    // 每次咋在上一个useEffect处理完以后再运行
    return () => clearTimeout(timeout);
  }, [value, delay]);
  return debounceValue;
};

// const debounce = (func, delay) => {
//     let timeout
//     return (...params) => {
//         if (timeout) {
//             clearTimeout(timeout)
//         }
//         timeout = setTimeout(() => {
//             func(...params)
//         }, 5000)
//     }
// }


export const useArray = <T> (initialArray: T[]) => {
  const [value, setValue] = useState(initialArray);
  return {
    value,
    setValue,
    add: (item: T) => setValue([...value, item]),
    clear: () => setValue([]),
    removeIndex: (index: number) => {
      const copy = [...value];
      copy.splice(index, 1);
      setValue(copy);
    }
  };
};

export const useDocumentTitle = (title: string, keepOnUnmount = true) => {
  const oldTitle = useRef(document.title).current;

  useEffect(() => {
    document.title = title;
  }, [title]);

  useEffect(() => {
    return () => {
      if (!keepOnUnmount) {
        document.title = oldTitle;
      }
    };
  }, [keepOnUnmount, oldTitle]);
};

export const resetRoute = () => window.location.href = window.location.origin;


/**
 * 传入一个对象，和键集合，返回对应的对象中的键值对
 * @param obj
 * @param keys
 */
export const subset = <O extends { [key in string]: unknown },
  K extends keyof O> (
    obj: O,
    keys: K[]
) => {
  const filterEntries = Object.entries(obj).filter(([key]) => {
    return keys.includes(key as K)
  })
  return Object.fromEntries(filterEntries) as Pick<O, K>
};

/**
 *  返回组件的挂载状态，如果还没挂载或者已经卸载，返回false，反之，返回true
 */
export const useMountedRef = () => {
  const mountedRef = useRef(false)
  useEffect(() =>{
    mountedRef.current = true
    return () => {
      mountedRef.current = false
    }
  })
  return mountedRef
}
